package com.xncoding.pos.controller.webfluxTest;

import com.xncoding.pos.dao.TbUserDao;
import com.xncoding.pos.model.TbUser;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * 在PersonHandler中处理对应的HTTP请求，等同于MVC架构中的Service层
 *函数式编程模型
 * 在使用函数式编程模型时，需要自己初始化服务器。
 * @Author guoyb
 * @Date 2024/1/30  11:06
 */
@Component
public class PersonHandler {

    @Resource
    private TbUserDao tbUserDao;

    public Mono<ServerResponse> listPeople(ServerRequest request) {
        List<TbUser> userList = tbUserDao.getAll();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(userList, TbUser.class);
    }

    public Mono<ServerResponse> createPerson(ServerRequest request) {
        Mono<TbUser> userMono = request.bodyToMono(TbUser.class);
        int insert = tbUserDao.insert(userMono.block());
        return ServerResponse.ok().build();
    }

    public Mono<ServerResponse> getPerson(ServerRequest request) {
        Long personId = Long.parseLong(request.pathVariable("id"));
        TbUser tbUser = tbUserDao.queryById(personId);
        return Mono.justOrEmpty(tbUser)
                .flatMap(person -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(person))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    //    http://localhost:8080/person/1


}
